#include "../source/client/requestor.hpp"
#include "../source/client/rpc_caller.hpp"
#include "../source/common/dispatcher.hpp"
//把服务注册 发现功能集合到客户端中
using namespace zyb_rpc;
using namespace std;
// using ConnectionCallback = std::function<void(const BaseConnection::ptr &)>;
// using CloseCallback = std::function<void(const BaseConnection::ptr &)>;
// using MessageCallback = std::function<void(const BaseConnection::ptr &, BaseMessage::ptr &)>;
void callback(const Json::Value &result)
{
    int res = result.asInt();
    cout << "result :" << res << endl;
}
int main()
{
    shared_ptr<client::Requestor> requestor = std::make_shared<client::Requestor>(); // 该模块类似rpctouter
    shared_ptr<client::RpcCaller> caller = std::make_shared<client::RpcCaller>(requestor);

    Dispatcher::ptr dispathcher = make_shared<Dispatcher>(); // 服务注册接口，提供给dispatcher的rpc响应处理回调函数
    auto rsp_cb = std::bind(&client::Requestor::onResponse, requestor.get(), std::placeholders::_1, std::placeholders::_2);
    // 客户端发送请求 收到响应后，最先经由dispatcher模块判断客户端是否注册了响应处理函数
    // 如果注册了。会先在Requestor处理响应是否正确，如果正确返回结果。如果不正确，打印日志信息。
    //  最后无论如何都会删除Requestor中对该次请求的描述，
    dispathcher->registerHandler<BaseMessage>(MType::RSP_RPC, rsp_cb);

    BaseClient::ptr client = ClientFactory::create("127.0.0.1", 9090);
    MessageCallback message_cb = std::bind(&Dispatcher::onMessage, dispathcher.get(),
                                           placeholders::_1, placeholders::_2);
    client->setMessageCallback(message_cb);
    client->connect();

    auto conn = client->connection();
    Json::Value params, result;
    params["num1"] = 11;
    params["num2"] = 22;
    bool ret = caller->call(conn, "Add", params, result);
    if (ret)
    {
        cout << "result :" << result.asInt() << endl;
    }

    Json::Value params1;
    client::RpcCaller::JsonAsyncResponse res_future; // std::future<Json::Value>
    params1["num1"] = 11;
    params1["num2"] = 22;
    ret = caller->call(conn, "Add", params1, res_future);
    if (ret)
    {
        int res = res_future.get().asInt();
        cout << "result :" << res << endl;
    }

    Json::Value params2;
    params2["num1"] = 11;
    params2["num2"] = 22;
    //  using RequestCallback = std::function<void(const BaseMessage::ptr &)>;

    ret = caller->call(conn, "Add", params2, callback);
    if (ret)
    {
    }
    std::this_thread::sleep_for(std::chrono::seconds(1));
    // 客户端通过RpcCaller的call 构建请求的描述，然后在RpcCaller的成员Requestor去实际发送信息，
    client->shutdown();
    return 0;
}
